﻿using System.Collections.Generic;
using System.Linq;
using SymbolIntegration.core.Helpers;

namespace SymbolIntegration.core.Expressions
{
    public class AddendsExpression : Expression
    {
        private ConstantExpression m_FirstConstant = new ConstantExpression(0);

        public ConstantExpression FirstConstant
        {
            get { return m_FirstConstant; }
        }

        private List<Expression> m_Addends = new List<Expression>();

        public List<Expression> Addends
        {
            get { return m_Addends; }
        }

        public static AddendsExpression GetByAddends(List<Expression> list, bool isNegate)
        {
            var addends = new AddendsExpression();
            addends = (AddendsExpression)addends.SetNegate(isNegate);
            list.Foreach(expression => addends.Add(expression));
            return addends;
        }

        internal static Expression ParseItself(string expression, int position, int size)
        {
            int oldPosition = position;
            int oldSize = size;
            var result = new AddendsExpression();
            ParseUtils.TrimScopes(expression, ref position, ref size);
            if (size == 0)
            {
                throw new ParseException("Expression is scopes or spaces. Need addend", expression, oldPosition, oldSize, 0);
            }

            int startExprPosition = position;
            bool isNextExpressionNegate = false;
            int i = position;
            if (expression[position] == '-')
            {
                i++;
            }

            for (; i < size + position; i++)
            {
                if (expression[i] == '(')
                {
                    i = ParseUtils.FindCloseScopePosition(expression, i, size + position - i);
                }
                if (expression[i] == '+' || expression[i] == '-')
                {
                    Expression addendExpression = ParseUtils.Parse(expression, startExprPosition, i - startExprPosition);
                    addendExpression = addendExpression.InvertNegate(isNextExpressionNegate);
                    isNextExpressionNegate = (expression[i] == '-');
                    result.Add(addendExpression);
                    startExprPosition = i + 1;
                }
            }
            Expression lastAddendExpression = ParseUtils.Parse(expression, startExprPosition, position + size - startExprPosition);
            lastAddendExpression = lastAddendExpression.InvertNegate(isNextExpressionNegate);
            result.Add(lastAddendExpression);
            return result;
        }

        public static AddendsExpression MulDistributed(List<Expression> multsList)
        {
            var addendsList = new List<Expression> {new ConstantExpression(1)};
            foreach (var expression in multsList)
            {
                var addednsExpr = expression as AddendsExpression;
                if (addednsExpr == null)
                {
                    addendsList = addendsList.Select(addendsExpression => addendsExpression*expression).ToList();
                }
                else
                {
                    var newAddendsList = new List<Expression>();
                    foreach (var addend in addendsList)
                    {
                        newAddendsList.AddRange(addednsExpr.m_Addends.Select(addendInOuterExpr => addendInOuterExpr*addend));
                        newAddendsList.Add(addednsExpr.m_FirstConstant * addend);
                    }
                    addendsList = newAddendsList;
                }
            }
            var result = new AddendsExpression();
            foreach (var expression in addendsList)
            {
                result.Add(expression);
            }
            return result;
        }

        public static AddendsExpression Add(Expression left, Expression right)
        {
            var result = new AddendsExpression();
            result.Add(left);
            result.Add(right);
            return result;
        }

        protected AddendsExpression()
        {
            
        }

        //protected override Expression NormalizeByVariable(string var)
        //{
        //    Expression result;
        //    do
        //    {
        //        var dependentsAddends = m_Addends.Where(expression => expression.IsDependsFrom(var));
        //        var undependentsAddends = m_Addends.Where(expression => !expression.IsDependsFrom(var)).ToList();
        //        undependentsAddends.Add(m_FirstConstant);

        //    } 
        //    while (false);

        //    return result;
        //}


        public override Expression Substitute(Dictionary<string, Expression> varValues)
        {
            var clone = new AddendsExpression();
            InnerCopy(clone);
            foreach (var expression in m_Addends)
            {
                clone.Add(expression.Substitute(varValues));
            }
            clone.AddConstant(m_FirstConstant);
            return clone;
        }

        public override Expression Differentiate(string variable)
        {
            Expression result;
            do
            {
                if (!IsDependsFrom(variable))
                {
                    result = new ConstantExpression(0);
                    break;
                }
                var addends = new AddendsExpression();
                foreach (var expression in m_Addends)
                {
                    addends.Add(expression.Differentiate(variable));
                }
                result = addends;
            } 
            while (false);
            InnerCopy(result);
            return result;
        }

        public override Expression Normalize()
        {
            Expression result;
            do
            {                
                //Normilize addends
                var normalAddends = new AddendsExpression();
                foreach (var expression in m_Addends)
                {
                    normalAddends.Add(expression.InvertNegate(IsNegate).Normalize());   
                }
                normalAddends.AddConstant((ConstantExpression)m_FirstConstant.InvertNegate(IsNegate).Normalize());
                var simply = normalAddends.TrySimplifyByConstant();
                if (simply != null)
                {
                    result = simply;
                    break;
                }

                var addendsList = new List<Expression>();
                //Merge equals multipliers
                foreach (var expression in normalAddends.m_Addends)
                {
                    MultipliersExpression.TryAddNormalizedExpression(addendsList, expression);
                }

                var finalNormalized = new AddendsExpression();
                foreach (var expression in addendsList)
                {
                    finalNormalized.Add(expression);
                }
                finalNormalized.AddConstant(normalAddends.m_FirstConstant);

                result = finalNormalized.TrySimplifyByConstant() ?? finalNormalized;
            } 
            while (false);

            return result;
        }

        public override bool IsEqual(Expression right)
        {
            bool result = false;
            do
            {
                if (right.IsNegate != IsNegate)
                {
                    break;
                }

                var addends = right as AddendsExpression;
                if (addends == null)
                {
                    break;
                }

                if (!IsListsEqual(m_Addends, addends.m_Addends))
                {
                    break;
                }

                if (!m_FirstConstant.IsEqual(addends.m_FirstConstant))
                {
                    break;
                }

                result = true;
            }
            while (false);

            return result;
        }

        public override Polinom FormatToPolinomAsDependentFromVariable(string variable)
        {
            Polinom polinom;
            do
            {
                polinom = new Polinom(variable);
                foreach (var addend in m_Addends)
                {
                    var addPolinom = addend.InvertNegate(IsNegate).FormatToPolinom(variable);

                    if (addPolinom == null)
                    {
                        polinom = null;
                        break;
                    }
                    polinom.Add(addPolinom);
                }
                if (polinom == null)
                {
                    break;
                }

                polinom.Add(m_FirstConstant.InvertNegate(IsNegate).Normalize().FormatToPolinom(variable));
            }
            while (false);
            return polinom;
        }

        public override Expression Clone()
        {
            var clone = new AddendsExpression
            {
                m_Addends = new List<Expression>(m_Addends.Select(expression => expression)),
                m_FirstConstant = m_FirstConstant
            };
            InnerCopy(clone);
            return clone;
        }

        public override ExpressionType Type
        {
            get { return ExpressionType.Addends; }
        }

        public override string ToString()
        {
            string result = "";
            do
            {
                if (m_Addends.Count == 0)
                {
                    result = m_FirstConstant.ToString();
                    break;
                }

                bool isFirst = true;
                foreach (var expression in m_Addends)
                {
                    if (!isFirst)
                    {
                        result += '+';
                    }
                    if (expression.IsNegate)
                    {
                        result += "(" + expression + ")";
                    }
                    else
                    {
                        result += expression;
                    }
                    isFirst = false;
                }

                if (!MathHelper.AlmostEqual(m_FirstConstant.Value, 0))
                {
                    result += '+' + m_FirstConstant.ToString();
                }
            } 
            while (false);

            if (IsNegate)
            {
                result = "-(" + result + ")";
            }

            return result;
        }

        protected internal override void RebuildDependancyCache()
        {
            m_Cache.Varibles.Clear();
            foreach (var expression in m_Addends)
            {
                if (!expression.m_Cache.IsValid)
                {
                    expression.RebuildDependancyCache();
                }
                m_Cache.Varibles.UnionWith(expression.m_Cache.Varibles);
            }

            m_Cache.IsValid = true;
        }

        protected internal override void FillExpressionStatistic(ExpressionStatistic statistic, string integrateVariable)
        {
            foreach (var expression in m_Addends)
            {
                expression.FillExpressionStatistic(statistic, integrateVariable);
            }
        }

        protected internal override Expression IntegrateAsDependentFromVar(string variable, IIntegrator integrator)
        {
            var intergatedAddends = new AddendsExpression();
            foreach (var expression in m_Addends)
            {
                intergatedAddends.Add(expression.Integrate(variable, integrator));
            }
            intergatedAddends.Add(m_FirstConstant.Integrate(variable, integrator));
            Expression result = intergatedAddends.SetNegate(IsNegate);
            return result;
        }

        protected void Add(Expression expression)
        {
            do
            {
                var constExpr = expression as ConstantExpression;
                if (constExpr != null)
                {
                    AddConstant(constExpr);
                    break;
                }

                var newExpression = expression as AddendsExpression;
                if (newExpression != null)
                {
                    m_Addends.AddRange(newExpression.m_Addends
                        .Select(expression1 => expression1.InvertNegate(newExpression.IsNegate)));
                    AddConstant(newExpression.m_FirstConstant.InvertNegate(newExpression.IsNegate) as ConstantExpression);
                }
                else
                {
                    m_Addends.Add(expression);
                }
            }
            while (false);
        }

        protected void AddConstant(ConstantExpression expression)
        {
            double leftVal = (expression.IsNegate ^ IsNegate) ? -expression.Value : expression.Value;
            double rightVal = m_FirstConstant.Value;

            m_FirstConstant = new ConstantExpression(leftVal + rightVal);
        }

        public Expression TrySimplifyByConstant()
        {
            Expression result = null;
            if (m_Addends.Count == 0)
            {
                result = m_FirstConstant.InvertNegate(IsNegate).Normalize();
            }

            if (m_Addends.Count == 1 && MathHelper.AlmostEqual(m_FirstConstant.Value, 0))
            {
                result = m_Addends.First().InvertNegate(IsNegate).Normalize();
            }
            return result;
        }
    }
}